// src/components/s-share/index.js
const App = getApp()
import { formatDate, formatCentMoney } from '../../utils/index'
import Canvas from '../../palette/drawer'
const drawer = new Canvas()
import { AppModel } from '../../models/app.js'
const ModelApp = new AppModel()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    visible: Boolean, // 显示隐藏
    sharedata: {
      type: Object,
      value: {
        showWay: '' // 不弹出底部分享栏
      },
      observer(newVal, oldVal) {
        // 如果type==progood或者managerme则直接调用生成分享图
        if (newVal && newVal.showWay == 'nobar') {
          this.shareDiscover()
        }
      }
    }, // 分享数据
    type: String, // 分享类型
    // mask背景透明
    transparent: {
      type: Boolean,
      value: false
    },
    showDiscover: {
      type: Boolean,
      value: true
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    showCanvas: false,
    painting: {},
    shareImage: '',
    canvasVisible: false,
    cache: {}
  },

  ready() {
    wx.removeStorageSync('code_img_cache')
    this.data.cache = wx.getStorageSync('code_img_cache') || {}
  },
  methods: {
    // 关闭share
    closeShare() {
      this.setData({
        visible: false
      })
      // 触发时不晃动分享icon
      this.triggerEvent('emitwiggle')
    },
    // 获取二维码，缓存里有就从缓存里拿
    getCacheImage(parmas) {
      const _this = this
      const url = parmas.page + parmas.scene
      return new Promise((resolve, reject) => {
        if (_this.data.cache[url]) {
          console.log('getCacheImage cache==' + url)
          resolve(_this.data.cache[url])
        } else {
          console.log('getCodeUrl', JSON.stringify(parmas))
          // 生成小程序二维码
          ModelApp.getCodeUrl(parmas)
            .then(res => {
              _this.data.cache[url] = res.codeUrl
              resolve(res.codeUrl)
            })
            .catch(err => {
              wx.showToast({
                title: '生成二维码失败,请稍后重试',
                icon: 'none'
              })
              App.globalData.bug.notifyError(JSON.stringify(err))
              reject(err)
            })
        }
      })
    },

    // 分享生成海报图
    shareDiscover() {
      const _this = this
      // 初始化图步
      const userInfo = App.globalData.userInfo
      const shareInfo = _this.properties.sharedata
      const type = _this.properties.type
      console.log(shareInfo)

      // 如果分享的是活动
      if (type === 'activity') {
        // 获取二维码
        const params = {
          scene: `${userInfo.userCode}&${shareInfo.specialCode}`,
          page: 'pages/activity/index',
          width: 340,
          auto_color: false,
          r: '0',
          g: '0',
          b: '0',
          is_hyaline: false
        }
        // 获取二维码
        _this
          .getCacheImage(params)
          .then(codeImg => {
            let template = drawer.activity(
              shareInfo.shareTitle,
              shareInfo.shareImg,
              userInfo.userImg, // 用户头像
              decodeURIComponent(userInfo.nickName), // 解码昵称
              formatDate(shareInfo.startDate, 'MM/dd'), // 格式化时间
              formatDate(shareInfo.endDate, 'MM/dd'), // 格式化时间,
              codeImg
            )
            // 渲染
            _this.render(template)
          })
          .catch(err => {
            console.log(err)
          })
      } else if (type === 'preactivity') {
        // 获取二维码
        const params = {
          scene: `${userInfo.userCode}&${shareInfo.specialCode}`,
          page: 'pages/trailer/index',
          width: 200,
          auto_color: false,
          r: '0',
          g: '0',
          b: '0',
          is_hyaline: false
        }
        // 获取二维码
        _this.getCacheImage(params).then(codeImg => {
          let template = drawer
            .activity(
              shareInfo.shareTitle,
              shareInfo.shareImg,
              userInfo.userImg, // 用户头像
              decodeURIComponent(userInfo.nickName), // 解码昵称
              formatDate(shareInfo.startDate, 'MM/dd'), // 格式化时间
              formatDate(shareInfo.endDate, 'MM/dd'), // 格式化时间,
              codeImg
            )
          // 渲染
          _this.render(template)
        }).catch(err => {})
      } else if (type === 'preactivitytohome') {
        // 获取二维码
        const params = {
          scene: userInfo.userCode,
          page: 'pages/home/index',
          width: 200,
          auto_color: false,
          r: '0',
          g: '0',
          b: '0',
          is_hyaline: false
        }
        // 获取二维码
        _this
          .getCacheImage(params)
          .then(codeImg => {
            let template = drawer.activity(
              shareInfo.shareTitle,
              shareInfo.shareImg, // 分享图5:4
              userInfo.userImg, // 用户头像
              decodeURIComponent(userInfo.nickName), // 解码昵称
              formatDate(shareInfo.startDate, 'MM/dd'), // 格式化时间
              formatDate(shareInfo.endDate, 'MM/dd'), // 格式化时间,
              codeImg
            )
            // 渲染
            _this.render(template)
          })
          .catch(err => {})
      } else if (type === 'goods') {
        // 如果分享的是商品
        const params = {
          scene: `${userInfo.userCode}&${shareInfo.id}&${shareInfo.specialCode}`,
          page: 'pages/goodsDetail/index',
          width: 340,
          auto_color: false,
          r: '0',
          g: '0',
          b: '0',
          is_hyaline: false
        }
        // 获取小程序二维码
        _this
          .getCacheImage(params)
          .then(codeImg => {
            let drawParams = {
              goodsName: shareInfo.goodsName,
              goodsImg: shareInfo.goodsImg,
              goodsMoney: formatCentMoney(shareInfo.goodsMoney), // 格式化打折之后金额
              goodsPrice: formatCentMoney(shareInfo.goodsPrice), // 格式化打折之后金额
              discount: shareInfo.discount.toFixed(1),
              codeImg: codeImg
            }
            // 秒杀,是快抢，而且是进行中 加几点开始字段
            if (shareInfo.modelStatus == 3 && shareInfo.specialStatus == 1) {
              drawParams.showTime = shareInfo.showTime
              // 专场商品 开始结束字段
            } else if (shareInfo.modelStatus == 2) {
              drawParams.startDate = formatDate(shareInfo.startDate, 'MM/dd') // 格式化时间专场商品有
              drawParams.endDate = formatDate(shareInfo.endDate, 'MM/dd') // 格式化时间专场商品有
            }
            let template = drawer.goods(drawParams)
            // 渲染
            _this.render(template)
          })
          .catch(err => {
            console.log(err)
          })
      } else if (type === 'progood') {
        // 生成无需二维码分享图
        let template = drawer.proGood(
          shareInfo.goodsName,
          shareInfo.goodsCode,
          shareInfo.size,
          shareInfo.goodsImg
        )
        // 渲染
        _this.render(template)
      } else if (type === 'home') {
        // 如果分享的是首页
        const params = {
          scene: userInfo.userCode,
          page: 'pages/home/index',
          width: 200,
          auto_color: false,
          r: '0',
          g: '0',
          b: '0',
          is_hyaline: false
        }
        // 获取小程序二维码
        _this
          .getCacheImage(params)
          .then(codeImg => {
            let template = drawer.home(
              userInfo.userImg,
              decodeURIComponent(userInfo.nickName), // 解码昵称
              codeImg
            )
            // 渲染
            _this.render(template)
          })
          .catch(err => {
            console.log(err)
          })
      } else if (type === 'index') {
        // 如果分享的是个人中心
        const params = {
          scene: userInfo.userCode,
          page: 'pages/home/index',
          width: 300,
          auto_color: false,
          r: '0',
          g: '0',
          b: '0',
          is_hyaline: false
        }
        // 获取小程序二维码
        _this
          .getCacheImage(params)
          .then(codeImg => {
            let template = drawer.index(codeImg, shareInfo.shareHomeImg)
            // 渲染
            _this.render(template)
          })
          .catch(err => {
            console.log(err)
          })
      } else if (type === 'red') {
        const params = {
          scene: `${userInfo.userCode}&${shareInfo.redId}`,
          page: 'pages/redpacket/index',
          width: 340,
          auto_color: false,
          r: '0',
          g: '0',
          b: '0',
          is_hyaline: false
        }
        // 获取小程序二维码
        _this
          .getCacheImage(params)
          .then(codeImg => {
            let template = drawer.red(
              userInfo.userImg,
              decodeURIComponent(userInfo.nickName), // 解码昵称
              codeImg
            )
            // 渲染
            _this.render(template)
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    render(template) {
      wx.showLoading({
        title: '生成专属二维码',
        mask: true
      })

      wx.setStorageSync('code_img_cache', this.data.cache)
      // 隐藏share btns,为图布设置值
      this.setData({
        visible: false, //
        painting: template
      })
    },
    // 生成图片成功
    eventGetImage(event) {
      wx.hideLoading()
      const { tempFilePath, errMsg } = event.detail
      // 如果只获得图片地址
      if (this.data.sharedata.mode == 'path') {
        this.triggerEvent('getPath', {
          tempFilePath: tempFilePath,
          errMsg: errMsg
        })
        return
      }
      if (errMsg === 'canvasdrawer:ok') {
        this.setData({
          canvasVisible: true,
          shareImage: tempFilePath
        })
        // 如果重复点击就直接显示
      } else if (errMsg === 'canvasdrawer:same params') {
        // 解决生成失败再次点击回不显示图片,显示按钮 if (tempFilePath) {}
        if (this.data.shareImage) {
          this.setData({
            canvasVisible: true
          })
        } else {
          wx.showToast({ title: '生成图片失败', icon: 'none' })
          App.globalData.bug.notifyError(
            new Error('canvasdrawer:same params err')
          )
        }
      } else {
        wx.showToast({ title: '生成图片失败', icon: 'none' })
        this.data.shareImage = ''
        App.globalData.bug.notifyError(new Error(errMsg))
      }
    }
  }
})
